package com.github.netty.day02_recycle;

import io.netty.util.Recycler;

public class UserPool {

  private static final Recycler<User> userRecycler = new Recycler<User>() {

    @Override

    protected User newObject(Handle<User> handle) {

      return new User(handle);

    }

  };

  static final class User {

    private String name;

    private Recycler.Handle<User> handle;

    public void setName(String name) {

      this.name = name;

    }

    public String getName() {

      return name;

    }

    public User(Recycler.Handle<User> handle) {

      this.handle = handle;

    }

    public void recycle() {

      handle.recycle(this);

    }

  }

  public static void main(String[] args) throws InterruptedException {

    User user = userRecycler.get();

    user.setName("json");

    new Thread(()->{
      user.recycle();
    }).start();


    Thread.sleep(1000);

    User userNext = userRecycler.get();

    System.out.println(userNext.getName());

    System.out.println(user == userNext);

  }

}